<?php

declare(strict_types=1);

namespace App\Http\Controllers\Manage;

use App\Repositories\Manage\ProductCategoryRepository;

class ProductCategoryController extends ManageBaseController
{

    private $categoryRepo = NULL;

    public function __construct(ProductCategoryRepository $categoryRepo)
    {
        parent::__construct();
        $this->categoryRepo = $categoryRepo;
    }

    public function index()
    {
        $res = getDeliveryTimes(date("H:i"));
        $filter = request()->all();
        if (!checkIsSuper(UID)) {
            $filter['shop_id'] = intval(getUserRelateShopId(UID));
        }
        $res = $this->categoryRepo->getList($filter, $this->pageNum, $this->pageSize);
        return retSuc($res);
    }

    public function detail($id)
    {
        $id = intval($id);
        if (!$id)
            return retFail("参数错误");
        $res = $this->categoryRepo->getOne($id);
        return retSuc($res);
    }

    /**
     * 清空待打印
     * @param $id
     */
    public function clear($id)
    {
        $id = intval($id);
        if (!$id)
            return retFail("参数错误");

        return $this->categoryRepo->clearPrinter($id);
    }

    /**
     * 初始化打印机
     * @param $id
     */
    public function init($id)
    {
        $id = intval($id);
        if (!$id)
            return retFail("参数错误");

        return $this->categoryRepo->initPrinter($id);
    }

    public function update($id = null)
    {
        $data = request()->only(['id', 'shop_id', 'title', 'sort', "status"]);

        if (!checkIsSuper(UID)) { //非超级会员
            $data['shop_id'] = intval(getUserRelateShopId(UID));
        }

        if ($this->categoryRepo->checkExistByTitle(intval($data['id'] ?? 0), $data['title'], intval($data['shop_id']))) {
            return retFail("分类名称已存在");
        }


        $last_id = $this->categoryRepo->saveOrUpdate($data, $id ?? 0);
        if (!$data['shop_id']) {
            return retFail("所属店铺必填");
        }
        if (!$last_id) {
            return retFail(empty($data['id']) ? "新增失败" : "更新失败");
        }

        $res = $this->categoryRepo->getOne(intval($last_id));
        return retSuc($res);
    }

    public function delete($id)
    {
        $id = intval($id);

        if (empty($id)) {
            return retFail("参数错误");
        }

        //        判断是否有权限
        if (!checkIsSuper(UID)) { //非超级会员
            $shop_id = intval(getUserRelateShopId(UID));
            if (empty($shop_id))
                return retFail("非法操作");
            $category = $this->categoryRepo->getOne($id);
            if (empty($category) || $category['shop_id'] !== $shop_id)
                return retFail("没有权限操作该分类");
        }

        return $this->categoryRepo->batchDelete($id);
    }

}
